package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class EditAccountFormServlet extends HttpServlet {

    private static final String EDIT_ACCOUNT = "/WEB-INF/jsp/account/EditAccount.jsp";
    private AccountService accountService;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String username = session.getAttribute("username").toString();

        accountService = new AccountService();
        Account account = accountService.getAccount(username);

        session.setAttribute("queriedAccount", account);
        if(account != null){
            HttpServletRequest httpRequest= request;
            String strBackUrl = "http://" + request.getServerName() + ":" + request.getServerPort()
                    + httpRequest.getContextPath() + httpRequest.getServletPath() + "?";

            LogService logService = new LogService();
            String logInfo = logService.logInfo(" ") + strBackUrl + EDIT_ACCOUNT;
            logService.insertLogInfo(account.getUsername(), logInfo);
        }
        request.getRequestDispatcher(EDIT_ACCOUNT).forward(request, response);
    }
}
